Operations

Let’s now see how we can manipulate and operate on data contained within our DataFrame. Table 1 and Table 2 respectively illustrate arithmetic and string-based operators that can be applied on parts of the DataFrame.

Numeric operations

Listing 1 Illustrates how to half the VEI column save the results to a new column.

Listing 1: Divide VEI by two and save the results to a new column.
df['VEI_halved'] = df['VEI'] / 2
Exercise

Longitudes are expressed as degrees E (i.e., from 0–180 ) and degrees W (i.e., from -180–0). Use operators to convert longitudes to degrees E (i.e., from 0–360) and store the results to a column called Longitude_E. To do so:

  1. Define a mask where Longitudes are negative using [logical operators]
  2. Where the mask is True (i.e. where the longitude is negative), add the longitude (or subtract its absolute value) to 360

Start by defining a mask

mask = df['Longitude'] <= 0

Select the values using .loc and do the maths.

360 + df.loc[mask, 'Longitude']
df.loc[mask, 'Longitude_E'] = 360 + df.loc[mask, 'Longitude']
Table 1: Common arithmetic operations on numerical pandas columns.
Operation Symbol Example Description
Addition + df['VEI'] + 1 Adds a value to each element
Subtraction - df['VEI'] - 1 Subtracts a value from each element
Multiplication * df['VEI'] * 2 Multiplies each element by a value
Division / df['VEI'] / 2 Divides each element by a value
Exponentiation ** df['VEI'] ** 2 Raises each element to a power
Modulo % df['VEI'] % 2 Remainder after division for each element

String operations

Table 2: Common string operations on pandas columns.
Operation Example Description
Concatenation df['Country'] + ' volcano' Adds a string to each element
String length df['Country'].str.len() Returns the length of each string
Uppercase df['Country'].str.upper() Converts each string to uppercase
Lowercase df['Country'].str.lower() Converts each string to lowercase
Replace df['Country'].str.replace('USA', 'US') Replaces substrings in each string